<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div v-loading="infoLoading" class="sign-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="detailInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" :style="`${showMobilePage ? 'margin-bottom: 0px' : ''}`" @queryProcessData="queryProcessData"/>
        <div :style="`${showMobilePage ? 'padding-top: 8px' : ''}`" class="sign-detail-content small-padding">
          <CancelInfo :data="detailInfo"/>
          <AccountInfo :data="detailInfo.linkSignUp"/>
          <ContractInfo :is-revoke="isRevoke" :id="terminationId" :data="detailInfo.linkContract" @freshData="querysignUpInfo"/>
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="infoLoading"
          :show-print="false"
          :process-id="processId"
          :main-id="terminationId"
          :version="version"
          :get-comments-api="getTerminationComments"
          :comment-add-api="addTerminationComment"
          :process-revocation-api="terminationRevocation"
          :process-recall-api="terminationRecall"
          :process-audit-api="terminationAudit"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.TERMINATION"
          :process-type="PROCESS_TYPE.TERMINATION"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="[createUser]"
          :approval-module-type="APPROVAL_MODULE_TYPE.TERMINATION"
          :show-contract-create-btn="Boolean(stepActiveId)"
          next-approve-module-id="terminationId"
          redirect-url="/supplierPage/terminationDetail"
          detail-page-router-name="terminationDetail"
          edit-page-router-name="terminationEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @handlePressSend="handlePressSend"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handleCreateNew="handleCreateNew('terminationEdit',{id: terminationId},{reapplyId: processId})"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('terminationEdit',{id: terminationId},{remodifyId: processId})"
          @handleCancelPress="handleCancelPress"
          @handleContractCreate="toLegalCreate"
        >
          <div v-if="!showMobilePage && stepActiveId" slot="signUp">
            <el-button type="primary" size="small" @click="toLegalCreate">发起合同审批</el-button>
          </div>
        </ExamineAndApprove>
      </template>
      <DeniedPlaceholder v-else />
      <ding-ding-dialog
        ref="pressSendDialogRef"
        :btn1="'确认加急'"
        :btn2="'取消'"
        :show-send-checkbox="false"
        :select-with-user-load="false"
        :default-list="pressDefaultList"
        redirect-url="/supplierPage/terminationDetail"
        summary-title="加急原因"
        title="催办通知"
        @handelOK="toSend" />
    </div>
  </div>
</template>
<script>
// 组件
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import CancelInfo from './module/cancelInfo';
import AccountInfo from './module/accountInfo';
import ContractInfo from './module/contractInfo';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { BUSINESS_TYPE, PROCESS_TYPE } from '@/utils/const/process';
import { hasRouteAuth } from '@/utils/permission';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
import revokeImg from '@/assets/auditProcess/process_status_3.png';
import emptyIcon from '@/assets/home/emptyIcon.png';
import { getTerminationDetail, addTerminationComment, getTerminationComments, terminationRevocation,
  terminationRecall, terminationAudit } from '@/api/termination';
import schedule from '@/mixins/schedule';

export default {
  components: { ProgressStep, explanation, ExamineAndApprove, CancelInfo, AccountInfo, ContractInfo },
  mixins: [schedule],
  data() {
    return {
      APPROVAL_MODULE_TYPE,
      revokeImg,
      emptyIcon,
      terminationId: '', // 解约单id
      processId: '', // 流程id
      detailInfo: {},
      infoLoading: false,
      BUSINESS_TYPE,
      PROGRESS_STEP,
      PROCESS_TYPE,
      getTerminationComments,
      addTerminationComment,
      terminationRevocation,
      terminationRecall,
      terminationAudit,
      permissionDenied: false, // 详情页是否可查看
      stepActiveId: PROGRESS_STEP.PENDING,
      processData: {// 流程信息
        list: [],
        operation: {
          auth: [],
          content: null
        }
      },
      isRevoke: false,
      operationSetEvents: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isCreate() { // 创建人
      return this.userInfo.id === this.detailInfo.createUserId;
    },
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    createUser() {
      let user = { id: this.detailInfo.createUserId, userName: this.detailInfo.createUser };
      if (this.isCreate) {
        user = this.userInfo;
      }
      return user;
    }
  },
  created() {
    this.initData();
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.terminationId = this.$route.query.terminationId;
      this.processId = this.$route.query.processId;
      if (!this.terminationId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    setProcessData(processData) {
      this.processData = processData;
      this.operationSetEvents = processData.operation.setEvents;
    },
    // 获取基本信息
    querysignUpInfo(callback = () => {}) {
      this.infoLoading = true;
      getTerminationDetail(this.terminationId).then(res => {
        this.infoLoading = false;
        this.handleProcessCheck(res.data.processId);
        if (res.code === 200) {
          if (res.data.linkContract && res.data.linkContract.length) {
            res.data.linkContract.forEach(i => {
              if (!i.proposerDepartmentName) i.proposerDepartmentName = i.proposerDepartment;
            });
          }
          if (res.data.processStatus === 3) { // 3为撤销
            this.stepActiveId = PROGRESS_STEP.PENDING;
            this.isRevoke = true;
          } else {
            this.isRevoke = false;
            this.stepActiveId = res.data.processStatus;
          }
          this.detailInfo = res.data;
          callback && callback();
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        callback && callback();
        this.infoLoading = false;
      });
    },
    queryProcessData() {
      this.querysignUpInfo();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    // 发起合同审批
    toLegalCreate() {
      if (this.detailInfo.linkSignUp && this.detailInfo.linkSignUp.accountsInfoList) {
        // 用于跳转到发起合同填充合作平台数据用
        localStorage.setItem('accountsInfoList', JSON.stringify(this.detailInfo.linkSignUp.accountsInfoList));
      }
      const mediumIds = (this.detailInfo.linkSignUp && this.detailInfo.linkSignUp.accountsInfoList || []).map(i => i.id).join();
      const url = this.$router.resolve({
        name: 'CreateContract',
        query: {
          type: 5,
          mediumIds,
          terminationId: this.terminationId
        }
      });
      window.open(url.href, '_blank');
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'termination' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    }
  }
};
</script>
<style lang="scss" scoped>
.sign-detail-container{
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 64px);
  .sign-detail-content{
    position: relative;
    padding: 0 24px 56px;
  }
  &::v-deep {
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
    .text {
      font-size: 14px;
      font-weight: 400;
      text-align: left;
      color: #999999;
      line-height: 20px;
      margin-top: 10px;
    }
    .blue {
      color: #406ef4;
    }
    img {
      width: 120px;
    }
  }
}
::v-deep .el-form-item__label {
  color: #999;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep .explanation {
  margin-bottom: 0;
}
::v-deep .el-pagination {
  padding: 0 !important;
  display: flex;
  align-items: center;
}
</style>
